import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    home: Scaffold(
      
      appBar: AppBar(title: Text("首页"),),
      body: MyHomePage()
    ),
  localizationsDelegates: [
    GlobalMaterialLocalizations.delegate, // 指定本地化的字符串和一些其他的值
    GlobalCupertinoLocalizations.delegate, // 对应的Cupertino风格
    GlobalWidgetsLocalizations.delegate // 指定默认的文本排列方向, 由左到右或由右到左
  ],
  supportedLocales: [
    Locale("en"),
    Locale("zh")
  ],
  
    );
  }
}

class MyHomePage extends StatefulWidget{
  @override
  MyHomePageState createState()=>MyHomePageState();
}
class MyHomePageState extends State<MyHomePage>{
var currentTime="请选择日期";
  @override
  Widget build(BuildContext context){
    return Center(
    child: Column(
      children: [
        Text("你好"),
        Text(currentTime),
        RaisedButton(
          child: Text("选择时间"),
          onPressed: (){
            showDatePicker(
              context: context,
              initialDate: DateTime.now(),
              firstDate: DateTime(2019),
              lastDate: DateTime(2022)
            ).then((pickTime){
                setState(){
                  currentTime=pickTime.toString();
                }
            });
          },
        )
      ],
    ),
  );
  }
}

///该类用于定义我们需要进行本地化的字符串等信息

class HYLocalizations{
  final Locale locale;
  //我们需要一个构造器，并且传入一个Locale对象（后续会使用到）
  HYLocalizations(this.locale);
  //定义一个Map，其中存放我们不同语言对应的显示文本
  static Map<String, Map<String,String>> _localizedValues = {
    "en":{
      "title":"home",
      "greet":"hello~",
      "pickname":"pick o time"
    },
    "zh":{
      "title":"首页",
      "greet":"你好~",
      "pickname":"选择一个时间"
    }
  };

//假如我们的数据是异步加载的，比如来自Json文件或者服务器，应该如何处理呢？
Future<bool> loadJson() async{
  //1、加载json文件
  String jsonString=await rootBundle.loadString("assets/json/i18n.json");

  final Map<String,dynamic> map= json.decode(jsonString);

 _localizedValues= map.map((key,value){
return MapEntry(key,value.cast<String,String>());
  });

  return true;
}

//定义它们对应的getter方法，根据语言环境返回不同的结果
  String get title{
    return _localizedValues[locale.languageCode]["title"];
  }

  String get greet{
    return _localizedValues[locale.languageCode]["greet"];
  }

  String get picktime{
    return _localizedValues[locale.languageCode]["picktime"];
  }
}


class HYLocalizationsDelegate extends LocalizationsDelegate<HYLocalizations>{

@override
  bool isSupported(Locale locale) {
    return ["en", "zh"].contains(locale.languageCode);
  }

  @override
  bool shouldReload(LocalizationsDelegate<HYLocalizations> old) {
    return false;
  }

  @override
  Future<HYLocalizations> load(Locale locale) {
    return SynchronousFuture(HYLocalizations(locale));
  }

//在HYLocalizationsDelegate中使用异步进行加载：
//  @override
//  Future<HYLocalizations> load(Locale locale) async {
//    final localization = HYLocalizations(locale);
//    await localization.loadJson();
//    return localization;
//  }

  static HYLocalizationsDelegate delegate = HYLocalizationsDelegate();
}



